/**
 * 
 */
package com.jushu.storbox.service;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;

import com.jushu.storbox.ShareDriveApplication;
import com.jushu.storbox.constant.Constant;
import com.jushu.storbox.database.DAOFactory;
import com.jushu.storbox.database.IFolderDao;
import com.jushu.storbox.entities.FileFolderInfo;
import com.jushu.storbox.entities.FileInfo;
import com.jushu.storbox.entities.FolderInfo;
import com.huawei.sharedrive.sdk.android.exception.ClientException;
import com.huawei.sharedrive.sdk.android.model.request.AsyncTaskINodeRequest;
import com.huawei.sharedrive.sdk.android.model.request.AsyncTaskRequest;
import com.huawei.sharedrive.sdk.android.model.request.FolderBaseRequest;
import com.huawei.sharedrive.sdk.android.model.request.FolderCreateRequest;
import com.huawei.sharedrive.sdk.android.modelV2.request.FolderCopyRequstV2;
import com.huawei.sharedrive.sdk.android.modelV2.request.FolderListRequestV2;
import com.huawei.sharedrive.sdk.android.modelV2.request.FolderMoveRequstV2;
import com.huawei.sharedrive.sdk.android.modelV2.request.FolderSearchRequestV2;
import com.huawei.sharedrive.sdk.android.modelV2.request.LinkCreateRequestV2;
import com.huawei.sharedrive.sdk.android.modelV2.request.Order;
import com.huawei.sharedrive.sdk.android.modelV2.response.FolderListResponseV2;
import com.huawei.sharedrive.sdk.android.modelV2.response.FolderResponse;
import com.huawei.sharedrive.sdk.android.modelV3.response.LinkInfoV3;
import com.huawei.sharedrive.sdk.android.service.handler.AsyncTaskHandler;
import com.huawei.sharedrive.sdk.android.serviceV2.FolderClientV2;
import com.huawei.sharedrive.sdk.android.serviceV2.LinkClientV2;
import com.huawei.sharedrive.sdk.android.serviceV3.LinkClientV3;

public class RemoteFolderService extends AbstractBaseService implements IRemoteFolderService
{
    /**
	 * 
	 */
    public RemoteFolderService()
    {
    }
    
    @Override
    public FolderResponse getFolderResponse(String ownerId, String folderId) throws ClientException
    {
    	FolderBaseRequest request = new FolderBaseRequest();
    	request.setFolderID(folderId);
    	request.setAuthorization(this.getAuthCode());
    	request.setOwnerID(ownerId);
    	FolderResponse response = FolderClientV2.getInstance().getFolderInfo(request);
    	return response;
    }
    
    @Override
    public FolderListResponseV2 getFolderListResponse(String folderID, String des, int limit, int offset,
        String orderby) throws ClientException
    {
        FolderListRequestV2 request = new FolderListRequestV2();
        request.setFolderID(folderID);
        request.setLimit(limit);
        request.setOffset(offset);
        request.setOwnerID(ShareDriveApplication.getInstance().getWnerID());
        
        Order o = new Order();
        o.setDirection(des);
        o.setField(orderby);
        List<Order> olist = new ArrayList<Order>();
        olist.add(o);
        request.setOrder(olist);
        shareDriveApplication.smartAuthorization();
        FolderListResponseV2 response = FolderClientV2.getInstance().getFolderInfoList(request,
            this.getAuthCode());
        
        return response;
    }
    
    public List<FileFolderInfo> getFolderList(Context context, String folderID, String des, int limit,
        int offset, String orderby) throws ClientException
    {
        FolderListRequestV2 request = new FolderListRequestV2();
        request.setFolderID(folderID);
        request.setLimit(limit);
        request.setOffset(offset);
        request.setOwnerID(ShareDriveApplication.getInstance().getWnerID());
        
        Order o = new Order();
        o.setDirection(des);
        o.setField(orderby);
        List<Order> olist = new ArrayList<Order>();
        olist.add(o);
        request.setOrder(olist);
        shareDriveApplication.smartAuthorization();
        final FolderListResponseV2 response = FolderClientV2.getInstance().getFolderInfoList(request,
            this.getAuthCode());
        
        List<FileFolderInfo> folderList = FileHelper.convertFolderRemoteToLocal(response);
        return folderList;
    }
    
    @Override
    public FolderResponse renameFolder(FileFolderInfo fileInformation, String name) throws ClientException
    {
        FolderBaseRequest request = new FolderBaseRequest();
        request.setAuthorization(ShareDriveApplication.getInstance().getAuthorization());
        request.setFolderID(fileInformation.getId());
        request.setOwnerID(fileInformation.getOwnerId());
        
        FolderResponse response = null;
        shareDriveApplication.smartAuthorization();
        response = FolderClientV2.getInstance().renameFolderInfo(request, name);
        return response;
    }
    
    @Override
    public FolderResponse renameFolderInfo(FolderBaseRequest request, String name) throws ClientException
    {
        shareDriveApplication.smartAuthorization();
        FolderResponse response = FolderClientV2.getInstance().renameFolderInfo(request, name);
        return response;
    }
    
    @Override
    public String deleteFolder(String ownerId, String folderID) throws ClientException
    {
        String response = "";
        FolderBaseRequest fbr = new FolderBaseRequest();
        fbr.setAuthorization(this.getAuthCode());
        fbr.setFolderID(folderID);
        fbr.setOwnerID(ownerId);
        shareDriveApplication.smartAuthorization();
        response = FolderClientV2.getInstance().deleteFolder(fbr);
        return response;
    }
    
    public String deleteFolder(FileFolderInfo fileFolderInfo) throws ClientException
    {
    	FolderBaseRequest fbr = new FolderBaseRequest();
		fbr.setAuthorization(ShareDriveApplication.getInstance()
				.getAuthorization());
		fbr.setFolderID(fileFolderInfo.getId());
		fbr.setOwnerID(fileFolderInfo.getOwnerBy());
		
        String deleteFolderRes = null;
        shareDriveApplication.smartAuthorization();
        deleteFolderRes = FolderClientV2.getInstance().deleteFolder(fbr);
        return deleteFolderRes;
    }
    
    public void deleteFolderAsyn(FileFolderInfo fileFolderInfomation, AsyncTaskHandler handler) throws ClientException
    {
    	Long OwnerId = Long.valueOf(fileFolderInfomation.getOwnerBy());
    	long nodeId = Long.valueOf(fileFolderInfomation.getId());
    	
    	AsyncTaskRequest folderToDeleteRequest = new AsyncTaskRequest();
        folderToDeleteRequest.setType("delete");
        folderToDeleteRequest.setSrcOwnerId(OwnerId);
        ArrayList<AsyncTaskINodeRequest> folderToDeleteList = new ArrayList<AsyncTaskINodeRequest>();
        AsyncTaskINodeRequest folderToDelete = new AsyncTaskINodeRequest(nodeId);
        folderToDeleteList.add(folderToDelete);
        folderToDeleteRequest.setSrcNodeList(folderToDeleteList);
        
    	shareDriveApplication.smartAuthorization();
		FolderClientV2.getInstance().deleteFolderAsy(shareDriveApplication.getAuthorization(), 
				folderToDeleteRequest, handler);
    }
    
    @Override
    public FolderListResponseV2 searchFolder(FolderSearchRequestV2 request) throws ClientException
    {
        shareDriveApplication.smartAuthorization();
        return FolderClientV2.getInstance().search(request, this.getAuthCode());
    }
    
    @Override
    public FileFolderInfo createFolder(Context context, String ownerId, FolderCreateRequest request) throws ClientException
    {
        shareDriveApplication.smartAuthorization();
        FolderResponse folderResponse = FolderClientV2.getInstance().create(ownerId,
            request,
            this.getAuthCode());
        return DAOFactory.instance(context).getFolderDao().insertFolder(folderResponse, 0);
    }
    
    @Override
    public FolderResponse moveFolder(FileFolderInfo fileFolderInfo, FileFolderInfo targetFolder) throws ClientException
    {
    	String targetId = "0";
    	if( targetFolder != null) {
    		targetId = targetFolder.getId();
    	}
    	FolderMoveRequstV2 request = new FolderMoveRequstV2();
        request.setDestParent(targetId);
        request.setDestOwnerId(targetFolder.getOwnerId());
        
        shareDriveApplication.smartAuthorization();
        return FolderClientV2.getInstance().moveFolder(fileFolderInfo.getOwnerId(),
        		fileFolderInfo.getId(),
	            this.getAuthCode(),
	            request);
    }
    
    @Override
    public FolderResponse copyFolder(String ownerId, String folderID, FolderCopyRequstV2 request) throws ClientException
    {
        FolderResponse response = FolderClientV2.getInstance().copyFolder(ownerId, folderID,
        	ShareDriveApplication.getInstance().getAuthorization(), request);
        return response;
    }
    
    @Override
    public boolean isUpdate(Context context, FileFolderInfo info) throws ClientException{
        return isUpdate(context,info.getOwnerId(), info.getId());
    }
    
    private boolean isUpdate(Context context, String ownerId, String id) throws ClientException {
        boolean isUpdate = false;
        FolderListRequestV2 request = new FolderListRequestV2();
        request.setFolderID(id);
        request.setLimit(1000);
        request.setOffset(0);
        request.setOwnerID(ownerId);
        
        Order o = new Order();
        o.setDirection("DESC");
        o.setField("modifiedAt");
        List<Order> olist = new ArrayList<Order>();
        olist.add(o);
        request.setOrder(olist);

        IFolderDao folderDao = DAOFactory.instance(context).getFolderDao();
        
        FolderInfo folderInfo = folderDao.getFolderById(ownerId, id);
        shareDriveApplication.smartAuthorization();
        FolderListResponseV2 response = FolderClientV2.getInstance().getFolderInfoList(request,
            ShareDriveApplication.getInstance().getAuthorization());
        
        if (null != response) {
            List<FolderInfo> localFolderList = ServiceFactory.instance(context)
                .getLocalFolderService()
                .getFolderList(ownerId, id);
            List<FileInfo> localFileList = ServiceFactory.instance(context)
                .getLocalFileService()
                .getFileList(ownerId, id);
            boolean isFileUpdate = FileHelper.isFileUpdate(context, response.getFiles(), localFileList);
            
            if (isFileUpdate) {
            	folderInfo.setContentSyncState(Constant.SYNC_STATUS_FALSE);
            	folderDao.updateLocalSaveState(folderInfo);
    			folderInfo.notifyChange();
                isUpdate = true;
                return true;
            }
            
            List<FolderResponse> folderResponseList = response.getFolders();
            boolean isFolderUpdate = FileHelper.isFolderUpdate(context,
                response.getFolders(),
                localFolderList);
            
            if (isFolderUpdate) {
            	folderInfo.setContentSyncState(Constant.SYNC_STATUS_FALSE);
            	folderDao.updateLocalSaveState(folderInfo);
    			folderInfo.notifyChange();
                isUpdate = true;
                return isUpdate;
            }
            
            for (FolderResponse folderResponse : folderResponseList) {
                boolean childUpdate = isUpdate(context, folderResponse.getOwnerBy(), folderResponse.getId());
                if (childUpdate) {
                	folderInfo.setContentSyncState(Constant.SYNC_STATUS_FALSE);
                	folderDao.updateLocalSaveState(folderInfo);
        			folderInfo.notifyChange();
                    return true;
                }
            }

        	folderInfo.setContentSyncState(Constant.SYNC_STATUS_TRUE);
			DAOFactory.instance(context).getFolderDao().updateLocalSaveState(folderInfo);
			folderInfo.notifyChange();
        }
        return isUpdate;
    }
    
    @Override
    public List<LinkInfoV3> getLink(FileFolderInfo fileInformation) throws ClientException
    {
        shareDriveApplication.smartAuthorization();
        List<LinkInfoV3> linkInfo = LinkClientV3.getInstance().getLink(ShareDriveApplication.getInstance()
            .getAuthorization(),
            fileInformation.getOwnerId(),
            fileInformation.getId());
        
        return linkInfo;
    }
    
    @Override
    public boolean isComplexLinkCode(String authorization) throws ClientException
    {
        shareDriveApplication.smartAuthorization();
    	return LinkClientV2.getInstance().isComplexLinkCode(authorization);
    }
    
    @Override
	public void deleteLink(FileFolderInfo fileInformation,String linkCode) throws ClientException {
        shareDriveApplication.smartAuthorization();
		LinkClientV3.getInstance().deleteLink(ShareDriveApplication.getInstance()
            .getAuthorization(), fileInformation.getOwnerBy(), fileInformation.getId(),linkCode);
	}
    
    @Override
    public LinkInfoV3 createLink(FileFolderInfo fileInformation) throws ClientException
    {
        LinkCreateRequestV2 request = new LinkCreateRequestV2();
        request.setRole(Constant.LINK_ROLE_VIEW);
        request.setAccess("");
        request.setAccessCodeMode("static");

        shareDriveApplication.smartAuthorization();
        LinkInfoV3 linkInfo = LinkClientV3.getInstance().createLink(ShareDriveApplication.getInstance()
            .getAuthorization(),
            fileInformation.getOwnerBy(),
            fileInformation.getId(),
            request);
        
        return linkInfo;
    }
    
    @Override
    public LinkInfoV3 updateLink(FileFolderInfo fileInformation, LinkCreateRequestV2 linkRequest) throws ClientException
    {
        shareDriveApplication.smartAuthorization();
        LinkInfoV3 linkInfo = LinkClientV3.getInstance().updateLink(ShareDriveApplication.getInstance()
            .getAuthorization(),
            fileInformation.getOwnerBy(),
            fileInformation.getId(),
            linkRequest);
        
        return linkInfo;
    }

}
